#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2024/11/21 16:09
# @Author : ZhengQL

import requests
from common.Yaml_Handler import YamlHandler
from common.Path_Handler import PathHandler

class RequestHandler:
    def __init__(self):
        """session"""
        self.session = requests.Session()


    def visit(self, method, url, params=None, data=None, json=None, headers=None,  **kwargs):
        """
        :param method: 请求方法
        :param url: 请求地址
        :param params: 请求参数
        :param data: 请求体
        :param json: json格式请求体
        :param headers: 请求头
        :param kwargs: 其他参数
        :return: 返回响应结果
        """
        result = self.session.request(method, url, params=params, json=json, data=data, headers=headers, verify = False)
        print(result)
        try:
            # 返回json结果
            return result.json()
        except Exception:
            return 'not json'

    def close_session(self):
        self.session.close()




if __name__ == '__main__':
    url = YamlHandler(PathHandler.config_path + r'/config.yaml').read_yaml()['login']['url']['url']
    headers = YamlHandler(PathHandler.config_path + r'/config.yaml').read_yaml()['login']['headers']
    print("YAML Data:", url)  # 打印 url# 内容
    print("YAML Data:", headers)  # 打印 header 内容

    payload2 = {
       'password':"YGmOb248cLw="
    }
    # ssl._create_default_https_context = ssl._create_unverified_context

    req = RequestHandler()
    login_res = req.visit("post",url=url,data=payload2,headers=headers)
    # 打印调试
    print(login_res)

    # 提取 access_token
    access_token = login_res['data']['access_token']

    # 创建会话对象
    session = requests.Session()

    # 将 access_token 保存到会话中
    session.headers.update({'Authorization': f'Bearer {access_token}'})
    print(f'获取的token：{access_token}')
